package com.shanzmoo.admin.config;

import com.shanzmoo.core.cache.CurrentUserCache;
import com.shanzmoo.admin.manager.SysUserManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;


/**
 * WebMvc 自定义配置
 *
 * @author: Gzhao 2020/11/8
 */
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private static final List<String> EXCLUDE_PATH = Arrays.asList(
            "/api/auth/login",
            "/swagger-ui.html",
            "/swagger-ui/*",
            "/swagger-resources/**",
            "/v2/api-docs",
            "/v3/api-docs",
            "/webjars/**",
            "/favicon.ico",
            "/swagger-ui",
            "/",
            "/csrf",
            "/error",
            "/open/**"
    );

    @Autowired
    private SysUserManager sysUserManager;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                     Object handler) throws Exception {
                log.info("WebMvcConfig-uri: {}", request.getRequestURI());
                // 用户登录缓存
                sysUserManager.obtainCurrentInfo();
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                                   ModelAndView modelAndView) throws Exception {
                CurrentUserCache.clear();
            }
        }).addPathPatterns("/**").excludePathPatterns(EXCLUDE_PATH);

    }
}
